<template>
  <div class="home">
    <h1>图书列表</h1>
    <button @click="fetchBooks">获取图书信息</button>
    <div class="results">
      <p v-if="books.length === 0">没有找到图书信息。</p>
      <ul v-else>
        <li v-for="book in books.slice(0, 5)" :key="book.id">
          <p><strong>书名:</strong> {{ book.bookName }}</p>
          <p><strong>作者:</strong> {{ book.author }}</p>
          <p><strong>出版社:</strong> {{ book.publishingHouse }}</p>
          <p><strong>出版日期:</strong> {{ formatDate(book.publishDate) }}</p>
          <p><strong>页数:</strong> {{ book.pages }}</p>
          <p><strong>ISBN:</strong> {{ book.ISBN }}</p>
          <p><strong>价格:</strong> {{ book.price }}</p>
          <hr>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      books: []
    };
  },
  methods: {
    async fetchBooks() {
      try {
        const response = await axios.get('http://localhost:8080/LibraryBack_war_exploded/books');
        this.books = response.data;
      } catch (error) {
        console.error('Error fetching books:', error);
        this.books = [];
      }
    },
    formatDate(date) {
      if (!date) return '无日期';
      const d = new Date(date);
      if (isNaN(d)) return '无效日期';
      return d.toLocaleDateString();
    }
  },
  mounted() {
    // Optionally, you can fetch books when the component is mounted.
    // this.fetchBooks();
  }
};
</script>

<style scoped>
.home {
  text-align: center;
}

.results {
  margin-top: 20px;
}

.results ul {
  list-style-type: none;
  padding: 0;
}

.results li {
  margin-bottom: 20px;
}

.results li p {
  margin: 5px 0;
}
</style>
